import React,{Component} from "react";
import { Steps, Form, Input, Button, Radio,DatePicker, message} from 'antd';
import { Link, withRouter } from 'react-router-dom';
import moment from 'moment';
import ajax from "../ajaxMethod";
import '../assets/stylesheets/register.css';
import  NodeRSA from 'node-rsa';
import config from "../config";
/*
repeatTestState
0：初始：可以按，文字：重复检测；字符小于4个
1：4个字符（只能是字母、数字和汉字的组合）后：可以按，文字：

重复检测
2：点击后：不可按，文字：5s倒计时
 */
class Register extends Component{
    constructor(props){
        super(props);
        this.state = {
            getCodeState: 0,
            time: 0,
            firstPageEnd: 0,
            //后面的是“第二页”的信息
            radioVal: 1,
            repeatTestState: 0,//0和2的时候是不能设置的,是否不能点击后的按钮，偶数可以点
            nameExist: true,
            secondPageEnd: 0,
        }
    }

    handleValidator = (rule, val, callback) =>{
        if(!val){ callback(); }
        let regEmail = new RegExp(/^[\w.\-]+@(?:[a-z0-9]+(?:-[a-z0-9]+)*\.)+[a-z]{2,3}$/);
        let regPhone = new RegExp(/^1[3|4|5|8]\d{9}$/);
        if(!regEmail.test(val) && !regPhone.test(val)){
            callback("请输入正确的电话号码或邮箱");
            this.setState({getCodeState: 0});
        }else{
            this.setState({getCodeState: 1});
        }
    }

    handleValidatorCode = (rule, val, callback) =>{
        if(!val){ callback(); }
        let reg = new RegExp(/\d{4}/);
        if(!reg.test(val)){
            callback("请输格式正确的验证码");
        }
    }
    //后面的是“第二页”的信息
    repeatTest = (e) => {
        let username = this.props.form.getFieldValue("username"),
            blank = false,
            _this = this;

        for(let i= 0; i < username.length; i++){
            if(' ' === username[i]){
                blank = true;
                break;
            }
        }
        if(blank === true){
            message.error("用户名不能含有空格");
        }
        else{
            //从后台检测这个用户名是否存在
            ajax.getAjax("/interface/repeatTest",{username: username},res=>{
                if(res.success){
                    console.log("检ce成功");
                    if(res.data.state){
                        message.warning("用户名已经存在");
                        setTimeout(() => {
                            _this.setState({repeatTestState: 1});
                        }, 5000);
                    }else{
                        message.success("用户名检测成功");
                        _this.setState({nameExist: false});
                        setTimeout(() => {
                            _this.setState({repeatTestState: 1, time: 0});
                        }, 5000);
                    }
                }else{
                    console.error(res.description);
                }
            }, err=>{
                console.error(err);
            })
            this.setState({repeatTestState: 0, time: 5});
            for(let i = 0; i < 5; i++){
                setTimeout(() => {
                    this.setState({time: this.state.time - 1});
                }, i * 1000);
            }
        }
    }
    userNameChange = (e) => {
        this.setState({nameExist :true});
    }
    handleValidatorName = (rule, val, callback) =>{
        //用户名的输入框
        if(val){
            val = val.replace(/\s+/g, "");
            if(!val){ callback("用户名不能为空"); }
            let reg = new RegExp(/([\u4e00-\u9fa5]|[a-z]|[A-Z]|[0-9]){4,16}/);
            if(reg.test(val)){
                this.setState({repeatTestState: 1});
            }
            else{
                callback("请输入4-16位字符的用户名并进行重复检测");
            }
        }else{
            callback("用户名不能有空格");
        }
    }
    handleValidatorPassword = (rule, val, callback) =>{
        if(val){
            if(val.length < 4 || val.length > 32){
                callback("请输入4-32位字符的密码");
            }
        }
    }
    handleValidatorRePassword = (rule, val, callback) =>{
        let password = this.props.form.getFieldValue("password");
        if(val !== password){
            callback("两次输入密码需要相同");
        }
    }
    disabledDate = (current)=> {
        // 只能选择今天之前的
        return current && current > moment().endOf('day');
    }
    handleSubmit = (e) =>{
        let values = this.props.form.getFieldsValue(),
            empty = false,
            _this = this,
            jsenc = new NodeRSA(config.publicKey);//设置密匙

        e.preventDefault();
        if(values.birthday){
            values.birthday = values.birthday.format("YYYY-MM-DD");
        }else{
            empty = true;
        }
        for(let item in values){
            if(item !== "repeat-test-btn" && item !== "gender" && !values[item]){
                empty = true; break;
            }
        }
        //密码要加密
        if(this.state.nameExist){
            message.warning("请先进行用户名重复检测");
        }else{
            if(!empty){
                delete values.rePassword;
                values.password = jsenc.encrypt(values.password, 'base64');

                ajax.postAjax("/interface/register", values, res=>{
                    if(res.success){
                        if(res.data.state === 1){
                            message.error("该邮箱已经注册，请直接登陆");
                        }else{
                            // message.success("成功注册第一步");
                            _this.props.history.push({
                                pathname:"/registerSecond"
                            })
                        }
                    }else{
                        console.error(res.description);
                    }
                },err=>{
                    console.log(err);
                });
            }else{
                message.error("请填写所有信息");
            }
        }
        this.props.form.validateFieldsAndScroll((err, values) => {//这个好像没什么用
            if (err) {
                console.error(err);
            }
        });
    }

    render(){
        console.log("state--",this.state);
        const {
            getFieldDecorator, getFieldsError, getFieldError, isFieldTouched,
        } = this.props.form;
        const formItemLayout = {
            labelCol: {
                // span: 4,
                // offset:24
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                // span: 4,
                // offset:4
                xs: { span: 24 },
                sm: { span: 8 },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 12,
                },
                sm: {
                    span: 16,
                    offset: 8,
                },
            },
        };
        const afterfix = getFieldDecorator('repeat-test-btn')(
            <button disabled={this.state.repeatTestState % 2 === 0 || this.state.time?true:false} onClick={this.repeatTest} >
                { !this.state.time? "重复检测": this.state.time + " 秒" }
            </button>
        )
        return(
        <div id="register">
            <div className="top">
                <div>
                    <Link to="/"><i className="logo"></i></Link>
                </div>
            </div>
            <div className="content-box">
                <div className="steps">
                    <Steps current={0}>
                        <Steps.Step title="信息填写" />
                        <Steps.Step title="验证" />
                        <Steps.Step title="完成" />
                    </Steps>
                </div>
                <Form onSubmit={this.handleSubmit} layout="horizontal">
                    <Form.Item
                        {...formItemLayout}
                        label="邮箱号"
                        >
                        {getFieldDecorator('account', {
                            rules: [
                                {required: true, message: '请输入邮箱' },
                                {validator: this.handleValidator}
                            ],
                        })(
                            <Input />
                        )}
                    </Form.Item>
                    <Form.Item
                        {...formItemLayout}
                        label="用户名"
                        validateStatus={this.state.nameExist?"warning":"success"}
                        hasFeedback
                        >
                        {getFieldDecorator('username', {
                            rules: [
                                {required: true, message: '请输入四个字符以上的用户名并进行重复检测' },
                                {validator: this.handleValidatorName}
                            ],
                        })(
                            // addonAfter={afterfix}
                            <Input addonAfter={afterfix}  placeholder='请输入4-16个字母/数字/汉字' onChange={this.userNameChange}/>
                        )}
                    </Form.Item>
                    <Form.Item
                        {...formItemLayout}
                        label="密码"
                        >
                        {getFieldDecorator('password', {
                            rules: [{
                                required: true, message: '请输入密码',
                            },{
                                validator: this.handleValidatorPassword
                            }], 
                        })(
                            <Input.Password placeholder='请输入4-32位的密码' visibilityToggle={false}/>
                        )}
                    </Form.Item>
                    <Form.Item
                        {...formItemLayout}
                        label="确认密码"
                        >
                        {getFieldDecorator('rePassword', {
                            rules: [{
                                required: true, message: '请重复输入密码',
                            },{
                                validator: this.handleValidatorRePassword
                            }],
                        })(
                            <Input.Password placeholder='请重复密码' visibilityToggle={false} />
                        )}
                    </Form.Item>
                    <Form.Item 
                        label="性别" 
                        {...formItemLayout} 
                        >
                        {getFieldDecorator('gender',{
                            initialValue: this.state.radioVal,
                        })(
                            <Radio.Group  name="radiogroup1" initialValue={0} onChange={this.radioChange}>
                                <Radio value={0}>男</Radio>
                                <Radio value={1}>女</Radio>
                            </Radio.Group>
                        )}
                    </Form.Item>
                    <Form.Item
                        {...formItemLayout}
                        label="出生日期"
                        >
                        {getFieldDecorator('birthday', {
                            initialValue: moment('2000/01/01', 'YYYY-MM-DD'),
                            rules: [{
                                required: true, message: '请输入出生日期',
                            }],
                        })(
                            <DatePicker disabledDate={this.disabledDate} placeholder="请选择日期" defaultValue={moment('2015/01/01', 'YYYY-MM-DD')}></DatePicker >
                        )}
                    </Form.Item>
                    <Form.Item {...tailFormItemLayout}>
                        <Button type="primary" htmlType="submit" className="login-form-button">提交信息</Button>
                    </Form.Item>
                </Form>
            </div>
        </div>)
    }
}

export default withRouter(Form.create({})(Register));